package com.cscec5b.inspection.service;

import com.cscec5b.inspection.dto.TaskInboundDtos.*;
import com.cscec5b.inspection.repository.DetailInspectionOriginalRepository;
import com.cscec5b.inspection.repository.TaskRepository;
import com.cscec5b.inspection.repository.TaskUpsertRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class TaskInboundService {

    private final TaskUpsertRepository taskRepo;
    private final DetailInspectionOriginalRepository detailRepo;
    private final ObjectMapper om = new ObjectMapper();

    public TaskInboundService(TaskUpsertRepository taskRepo, DetailInspectionOriginalRepository detailRepo) {
        this.taskRepo = taskRepo;
        this.detailRepo = detailRepo;
    }


    public TaskInboundResponse receive(TaskInboundRequest req) {
        /**
         * 接收上游系统发送的”任务同步“命令并入库
         */
        List<TaskResult> results = new ArrayList<>(req.data.size());

        for (TaskItem t : req.data) {
            boolean taskOk = true;
            List<InspectItemResult> itemResults = new ArrayList<>();

            try {
                String taskTypeEn = toEnglishType(t.inspect_type);
                String volJson    = toJson(t.inspect_batch_volume);
                String designJson = toJson(t.design_values);

                taskRepo.upsertTask(
                        t.task_id,
                        t.project_inner_number,
                        t.subproject_name,
                        t.inspect_rule,
                        taskTypeEn,
                        t.inspect_batch_part,
                        volJson,
                        designJson
                );

                for (InspectItem ii : t.inspect_items) {
                    try {
                        String membersJson = toJson(ii.members);
                        detailRepo.upsert(t.task_id.longValue(), ii.task_item_id, ii.fail_resample,  // task_item_id是上游系统的任务项主键
                                ii.inspect_item_id, ii.inspect_name, membersJson, ii.data_type);
                        itemResults.add(new InspectItemResult(ii.task_item_id, true, null));
                    } catch (Exception ex) {
                        taskOk = false;
                        itemResults.add(new InspectItemResult(ii.task_item_id, false, ex.getMessage()));
                    }
                }
            } catch (Exception e) {
                taskOk = false;
            }
            results.add(new TaskResult(t.task_id, taskOk, itemResults));
        }

        return new TaskInboundResponse(results);
    }

    private String toJson(Object o) {
        try { return om.writeValueAsString(o); }
        catch (Exception e) { throw new IllegalArgumentException("serialize json failed"); }
    }

    // 简单的中文→英文类别映射，按需补充；未知时返回拼音风格的 slug
    private static final Map<String,String> TYPE_MAP = Map.ofEntries(
            Map.entry("钢筋", "rebar"),
            Map.entry("混凝土", "concrete"),
            Map.entry("模板", "formwork"),
            Map.entry("砌筑", "masonry"),
            Map.entry("焊接", "welding"),
            Map.entry("防水", "waterproofing"),
            Map.entry("墙", "wall"),
            Map.entry("柱", "column"),
            Map.entry("梁", "beam"),
            Map.entry("板", "slab"),
            Map.entry("电梯井", "elevator_shaft"),
            Map.entry("独立基础", "isolated_foundation")
    );

    private String toEnglishType(String zh) {
        if (zh == null || zh.isBlank()) return "unknown";
        String v = zh.trim();
        if (TYPE_MAP.containsKey(v)) return TYPE_MAP.get(v);
        // 简单 slug：去空白/标点，英文数字保留，其余替换为下划线
        StringBuilder sb = new StringBuilder();
        for (char c : v.toCharArray()) {
            if (c <= 127 && (Character.isLetterOrDigit(c) || c==' ' || c=='-' || c=='_')) {
                sb.append(c);
            } else {
                sb.append('_');
            }
        }
        return sb.toString().replaceAll("\\s+","_").replaceAll("_+","_").toLowerCase();
    }
}
